'use strict';
const express = require('express');
const router = express.Router();
const resUtil = require('../module/util/resUtil');
const extend = require('extend');
const request = require('request');
const sha1 = require('sha1');
const xml2json = require('basic-xml2json');
const tool = require('../module/util/tool');
const logger = require('log4js').getLogger('sys');


router.use('*', function (req, res, next) {
    let language,
        appid = req.query.gId || req.session.gId,
        orgCode = req.query.orgCode || req.session.orgCode,
        wechatUtil;
    req.viewParam = {};
    req.viewParam.linkFlag = req.query.linkFlag || 0;

    let theme = req.query.brand, type;

    if (orgCode) {
        req.session.orgCode = orgCode;
        req.viewParam.orgCode = orgCode;
    }
    console.log('param', JSON.stringify(req.query));
    type = global.systemConstant.path[theme] || global.systemConstant.path.tgp;
    req.viewParam.imgPath = type.imgPath;
    req.viewParam.stylePath = type.style;
    req.viewParam.linkPath = type.link;
    req.viewParam.brandId = type.brandId;
    req.viewParam.brand = theme;
    req.viewParam.publicId = req.query.publicId;
    req.viewParam.gId = req.query.gId;
    req.viewParam.openId = req.query.openId;
    req.viewParam.gIdMap = global.systemConstant.G_ID_MAP;
    language = req.headers["accept-language"] || 'zh-CN';
    req.setLocale(language.substr(0, 2));
    // req.endType = "";
    req.endType = global.util.endType(req.headers['user-agent']);

    req.defaultParam = {
        path: null,
        redirect: null,
        data: req.query || {},
        body: {},
        userData: req.session[req.query.publicId],
        cookie: req.cookies
    };

    if (appid) {
        wechatUtil = global.cache.officialAccount[appid];
        req.session.gId = appid;
        if (!wechatUtil) {
            console.log(appid, '------');
            res.send('<html><meta name="viewport" content="width=device-width,initial-scale=1,user-scalable=0"><body ontouchstart>未找到正确的公众号配置，请联系管理员</body></html>');
        } else {
            let getCustomerInfoByWxId = (openId, publicId) => {
                if(!publicId){
                    publicId = '00000000';
                }
                req.session.publicId = req.query.publicId;
                global.util.getCustomerInfoByWxIdFromRedis(openId, publicId, function (json) {
                    req.session[publicId] = {};
                    extend(req.session[publicId], json.ResultValue[0].errMsg.List[0]);
                    req.viewParam.userData = json.ResultValue[0].errMsg.List[0];
                    req.viewParam.cardCode = req.viewParam.userData.cardCode;
                    wechatUtil.getCustomerInfo(openId).then(data => {
                        extend(req.session[publicId], data);
                        req.curUser = req.session[publicId];
                        console.log('----------------用户信息------------');
                        console.log(data);
                        console.log('----------------用户信息------------');
                        next();
                    }, err => {
                        console.error(err);
                        next();
                    });
                }, function (err) {
                    switch (err.type) {
                        case 'requestError':
                            res.send('<html><meta name="viewport" content="width=device-wid     th,initial-scale=1,user-scalable=0"><body ontouchstart>亲，内部网络有些不给力哦，重新点开吧:)</body></html>');
                            break;
                        case 'paramError':
                            res.send('<html><meta name="viewport" content="width=device-width,initial-scale=1,user-scalable=0"><body ontouchstart>未找到正确的公众号配置，请联系管理员</body></html>');
                            break;
                        case 'userNotFound':
                            //跳转到登录页面上去
                            logger.info('在这里第2次获得了openid-------' + req.viewParam.openId);
                            req.viewParam.openId = openId;
                            res.render('login', extend({}, req.defaultParam, {
                                body: req.viewParam,
                                userData: {
                                    openid: openId
                                }
                            }));
                            // res.redirect(req.viewParam.linkPath + '/login?openId=' + openId + '&orgCode=' + orgCode);
                            break;
                        default:
                            res.send('<html><meta name="viewport" content="width=device-width,initial-scale=1,user-scalable=0"><body ontouchstart>亲，内部环境网络有些不给力哦，重新点开吧:)</body></html>');
                    }
                });
            };

            let skipFromCache = function (publicId) {
                console.log(req.session[publicId]);
                global.util.getCustomerInfoByWxIdFromRedis(req.session[publicId]['openid'], publicId, function (json) {
                    extend(req.session[publicId], json.ResultValue[0].errMsg.List[0]);
                    req.viewParam.userData = req.session[publicId];
                    req.viewParam.cardCode = req.viewParam.userData.cardCode;
                    req.curUser = req.session[publicId];
                    next();
                })
            };

            if (req.query.store === '1') {
                if (req.query.latitude) {
                    request({
                        method: 'get',
                        uri: `${global.config.pos.endpoint}/getOrgInfoNew?orgBrand=${req.viewParam.brandId}&pageIndex=1&pageSize=10000`,
                        // uri: `http://www.keepright-pos.com:7474/LenLeWebWeixinNew/WeixinService.asmx/getOrgInfoNew?orgBrand=${req.viewParam.brandId}&pageIndex=1&pageSize=10000`,
                        json: true
                    }, function (e, response, data) {
                        if (!data) {
                            res.send(resUtil.error({message: "数据出错啦。请稍后再试"}));
                            return;
                        }
                        let jsonStr = xml2json.parse(data);
                        if (!jsonStr) {
                            res.send(resUtil.error({message: "数据出错啦。请稍后再试"}));
                            return;
                        }
                        if (!jsonStr.root) {
                            res.send(resUtil.error({message: "数据出错啦。请稍后再试"}));
                            return;
                        }
                        try {
                            let _str = jsonStr.root.content.replace('\n', '');
                            console.log('-=-=-=-=-=- latitude -=-=-=-=-=-');
                            console.log('_str', _str);
                            console.log('-=-=-=-=-=- latitude -=-=-=-=-=-');
                            let json = JSON.parse(_str);
                            let storeArr = json.ResultValue[0].errMsg.List;
                            let tempArr = [];
                            storeArr.forEach(function (value, index, array) {
                                if (value.parentOrgCode == req.query.orgCode && value.state == '正常') {
                                    value.distence = tool.getGreatCircleDistance(value.latitude, value.longitude, req.query.latitude, req.query.longitude);
                                    tempArr.push(value)
                                }
                            });
                            tempArr.sort(tool.compare('distence'));
                            // console.log(tempArr);
                            // console.log('-----------TT--------------');
                            res.render('closeShop', extend({}, req.defaultParam, {
                                body: tempArr,
                                userData: (req.query.publicId && req.session[req.query.publicId]) || {},
                                result: tempArr || [],
                                limitNumber: req.query.limitNumber || tempArr.length
                            }));
                        } catch (e) {
                            console.log(e);
                        }
                    });
                } else {
                    let timestamp = Date.parse(new Date()),
                        t = timestamp / 1000;
                    wechatUtil.getTicket(function (ticket) {
                        let key = [];
                        key.push("jsapi_ticket=" + ticket);
                        key.push("noncestr=a" + t);
                        key.push("timestamp=" + t);
                        if (req.query.limitNumber) {
                            console.log("url=http://keepright.fafa.com.cn" + global.config.path.contextPath + `/view/getPosition?brand=${req.query.brand}&limitNumber=${req.query.limitNumber}&orgCode=${req.query.orgCode}&gId=${req.query.gId}&store=1&code=${req.query.code}&state=${req.query.state}`);
                            key.push("url=http://keepright.fafa.com.cn" + global.config.path.contextPath + `/view/getPosition?brand=${req.query.brand}&limitNumber=${req.query.limitNumber}&orgCode=${req.query.orgCode}&gId=${req.query.gId}&store=1&code=${req.query.code}&state=${req.query.state}`);
                        } else {
                            key.push("url=http://keepright.fafa.com.cn" + global.config.path.contextPath + `/view/getPosition?brand=${req.query.brand}&orgCode=${req.query.orgCode}&gId=${req.query.gId}&store=1&code=${req.query.code}&state=${req.query.state}`);
                        }
                        let str = sha1(key.join("&"));
                        console.log(key.join("&"), str);
                        let configData = {
                            appId: wechatUtil.opts.appID,
                            timestamp: t,
                            nonceStr: "a" + t,
                            signature: str,
                            orgBrand: req.viewParam.brandId,
                            limitNumber: req.query.limitNumber
                        };
                        console.log(configData);
                        res.render('getPosition', extend({}, req.defaultParam, {
                            body: configData,
                            userData: (req.query.publicId && req.session[req.query.publicId]) || {}
                        }));
                    })
                }

            } else if (req.query.store == '2') {
                request({
                    method: 'get',
                    // uri: `${global.config.pos.endpoint}/getPromoInfo?orgCode=${req.query.orgCode}`,
                    uri: `http://www.keepright-pos.com:7474/LenLeWebWeixinNew/WeixinService.asmx/getPromoInfo?orgCode=${req.query.orgCode}`,
                    json: true,
                }, function (e, response, data) {
                    if (!data) {
                        res.send(resUtil.error({}));
                        return;
                    }
                    try {
                        let jsonStr = xml2json.parse(data);
                        let _str = jsonStr.root.content.replace('\\', '');
                        let json = JSON.parse(_str);
                        //1 {"ResultCode":"1","ResultValue":[{"errMsg":"查询提示:没有找到查询结果"}]}
                        //0 {"ResultCode":"0","ResultValue":[{"errMsg":{"currSaving":164.80,"flow":[{"2017-08-10":"后台充值储值增加[400]"},{"2017-08-21":"前台储值卡付款储值减少[184]"}]}}]}
                        let detailArr = json.ResultValue[0].errMsg.List;
                        res.render('detail', extend({}, req.defaultParam, {
                            body: req.viewParam,
                            userData: (req.session.publicId && req.session[req.session.publicId]) || {},
                            result: detailArr || false
                        }));
                    } catch (e) {
                        console.log(e);
                    }
                });
            } else {
                console.log(req.query.openId, req.query.publicId, '--------------------------', req.session[req.query.publicId]);
                if (req.query.openId && req.query.publicId) {
                    if (req.session[req.query.publicId] && req.session[req.query.publicId].openid) {
                        skipFromCache(req.query.publicId);
                    } else {
                        getCustomerInfoByWxId(req.query.openId, req.query.publicId);
                    }
                } else if (req.query.openId) {
                    if (req.session[req.query.publicId] && req.session[req.query.publicId].openid) {
                        skipFromCache(req.query.publicId);
                    } else {
                        getCustomerInfoByWxId(req.query.openId, null);
                    }
                } else if (req.query.code) {
                    logger.info("code: " + req.query.code, req.query.publicId);
                    if (req.session[req.query.publicId] && req.session[req.query.publicId].openid) {
                        skipFromCache(req.query.publicId);
                    } else {
                        wechatUtil.getOpenidByCode(req.query.code)
                            .then(function (openId) {
                                req.viewParam.openId = openId;
                                logger.info('在这里第一次获得了openid-------' + req.viewParam.openId);
                                getCustomerInfoByWxId(openId, req.query.publicId);
                            }, function (err) {
                                res.send('<html><meta name="viewport" content="width=device-width,initial-scale=1,user-scalable=0"><body ontouchstart>亲，网络有些不给力哦，重新点开吧:)</body></html>');
                            });
                    }
                } else {
                    next()
                    // res.send('<html><meta name="viewport" content="width=device-width,initial-scale=1,user-scalable=0"><body ontouchstart>您的参数错误</body></html>');
                }
            }

        }
    } else {
        res.send('<html><meta name="viewport" content="width=device-width,initial-scale=1,user-scalable=0"><body ontouchstart>未找到gid的配置，请确认配置正确</body></html>');
    }
});


module.exports = router;
